package com.sys.controller;

import com.utils.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * 文件接口
 */
@RestController
@RequestMapping("/file")
public class FileController {

    // 文件上传存储路径

    @Value("${server.port:9090}")
    private String port;

    @Value("${ip:localhost}")
    private String ip;

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file) {
        String fileName =null;
        try {


        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        File path = new File(ResourceUtils.getURL("classpath:static").getPath());
        if (!path.exists()) {
            path = new File("");
        }
        File upload = new File(path.getAbsolutePath(), "/upload/");
        if (!upload.exists()) {
            upload.mkdirs();
        }
         fileName = System.currentTimeMillis() + "." + fileExt;
        File dest = new File(upload.getAbsolutePath() + "/" + fileName);
        File dest2 = new File("/Users/zhangqiang/java_pro/2024/abo-cloud/abo-cloud-template/enterprise-assets-cloud-sys/src/main/resources/static/upload" + "/" + fileName);
        if(!dest2.exists()){
            dest2.createNewFile();
        }

        file.transferTo(dest);


            // 创建文件输入流
            FileInputStream inputStream = new FileInputStream(dest);
            // 创建文件输出流
            FileOutputStream outputStream = new FileOutputStream(dest2);

            // 缓冲区大小为 1KB
            byte[] buffer = new byte[1024];
            int bytesRead;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                // 从输入流读取数据并写入输出流
                outputStream.write(buffer, 0, bytesRead);
            }
            // 关闭输入流和输出流
            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            System.out.println("文件复制失败，请检查路径是否正确！");
        }
        return R.ok().put("file",fileName);
    }


    /**
     * 获取文件
     *
     * @param flag
     * @param response
     */



}
